package com.bzframework.project.api.job;

import com.bzframework.pro.api.core.manager.ApiSupportManager;
import com.bzframework.project.api.configuration.ProtocolProperties;
import com.bzframework.project.api.service.OpenApiProtocolService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.file.Path;
import java.nio.file.Paths;

@Component
@RequiredArgsConstructor
public class AutoLoadApiProtocolManager implements CommandLineRunner {

    private final OpenApiProtocolService openApiProtocolService;

    private final ApiSupportManager apiSupportManager;

    private final ProtocolProperties protocolProperties;

    @Override
    public void run(String... args) throws Exception {
        String baseStoragePath = protocolProperties.getBaseStoragePath();
        openApiProtocolService.createQuery()
                .fetch()
                .flatMap(protocol -> {
                    String id = protocol.getId();
                    String location = protocol.getLocation();
                    Path path = Paths.get(baseStoragePath, location);
                    String absolutePath = path.toFile().getAbsolutePath();
                    return apiSupportManager
                            .loadJar(id, absolutePath)
                            .collectList()
                            .flatMap(apiSupports -> Mono.fromRunnable(() -> apiSupportManager.register(id, apiSupports)));
                })
                .onErrorComplete()
                .subscribe();

    }
}
